/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ManutencaoCotacaoView.java
 *
 * Created on 27/06/2011, 21:21:29
 */

package br.com.comprasPublicas.view.cadastro;

import br.com.comprasPublicas.dao.DAOGenerico;
import br.com.comprasPublicas.dao.DAOManutencaoCotacao;
import br.com.comprasPublicas.entity.Cotacao;
import br.com.comprasPublicas.entity.InclusaoPrecosCotacao;
import br.com.comprasPublicas.entity.ItemPedido;
import br.com.comprasPublicas.entity.Pedido;
import br.com.comprasPublicas.entity.Pessoa;
import br.com.comprasPublicas.util.ConexaoReport;
import br.com.comprasPublicas.util.HibernateUtil;
import br.com.comprasPublicas.view.pesquisa.PesquisaManutencaoCotacaoView;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author helsen
 */
public class ManutencaoCotacaoView extends javax.swing.JFrame {


    /** Creates new form ManutencaoCotacaoView */
    public ManutencaoCotacaoView() {
        initComponents();
        btnConsultar.setEnabled(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        ftxtEmissao = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        ftxtVencimento = new javax.swing.JFormattedTextField();
        ftxtHoraVencimento = new javax.swing.JFormattedTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtPedido = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        txtCondPgto = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        txtCondEntrega = new javax.swing.JTextField();
        pnlDadosSolicitante = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        txtDescDepartamento = new javax.swing.JTextField();
        txtDescSecao = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblFornecedor = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblItemPedido = new javax.swing.JTable();
        btnVoltar = new javax.swing.JButton();
        pnlBotoes = new javax.swing.JPanel();
        btnConsultar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N
        setResizable(false);
        setUndecorated(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(br.com.comprasPublicas.compraspublicas.ComprasPublicasApp.class).getContext().getResourceMap(ManutencaoCotacaoView.class);
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        txtCodigo.setEditable(false);
        txtCodigo.setName("txtCodigo"); // NOI18N
        txtCodigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCodigoFocusLost(evt);
            }
        });

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        ftxtEmissao.setEditable(false);
        ftxtEmissao.setName("ftxtEmissao"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        ftxtVencimento.setEditable(false);
        ftxtVencimento.setName("ftxtVencimento"); // NOI18N

        ftxtHoraVencimento.setEditable(false);
        ftxtHoraVencimento.setName("ftxtHoraVencimento"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setFont(resourceMap.getFont("jLabel6.font")); // NOI18N
        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        txtPedido.setEditable(false);
        txtPedido.setName("txtPedido"); // NOI18N

        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        txtCondPgto.setEditable(false);
        txtCondPgto.setName("txtCondPgto"); // NOI18N

        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N

        txtCondEntrega.setEditable(false);
        txtCondEntrega.setName("txtCondEntrega"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCondPgto, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCondEntrega, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addGap(2, 2, 2)
                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ftxtEmissao, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ftxtVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ftxtHoraVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(ftxtEmissao, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(ftxtVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(ftxtHoraVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(txtCondPgto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(txtCondEntrega, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        pnlDadosSolicitante.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("pnlDadosSolicitante.border.title"))); // NOI18N
        pnlDadosSolicitante.setName("pnlDadosSolicitante"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        txtDescDepartamento.setEditable(false);
        txtDescDepartamento.setName("txtDescDepartamento"); // NOI18N

        txtDescSecao.setEditable(false);
        txtDescSecao.setName("txtDescSecao"); // NOI18N

        javax.swing.GroupLayout pnlDadosSolicitanteLayout = new javax.swing.GroupLayout(pnlDadosSolicitante);
        pnlDadosSolicitante.setLayout(pnlDadosSolicitanteLayout);
        pnlDadosSolicitanteLayout.setHorizontalGroup(
            pnlDadosSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDadosSolicitanteLayout.createSequentialGroup()
                .addGroup(pnlDadosSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addGap(16, 16, 16)
                .addGroup(pnlDadosSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtDescSecao, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                    .addComponent(txtDescDepartamento, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnlDadosSolicitanteLayout.setVerticalGroup(
            pnlDadosSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDadosSolicitanteLayout.createSequentialGroup()
                .addGroup(pnlDadosSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtDescDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlDadosSolicitanteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDescSecao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)))
        );

        jScrollPane3.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPane3.border.title"))); // NOI18N
        jScrollPane3.setName("jScrollPane3"); // NOI18N

        tblFornecedor.setAutoCreateRowSorter(true);
        tblFornecedor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod.", "Fornecedor"
            }
        ));
        tblFornecedor.setDropMode(javax.swing.DropMode.INSERT_ROWS);
        tblFornecedor.setName("tblFornecedor"); // NOI18N
        tblFornecedor.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        tblFornecedor.getTableHeader().setResizingAllowed(false);
        tblFornecedor.getTableHeader().setReorderingAllowed(false);
        tblFornecedor.setUpdateSelectionOnSort(false);
        tblFornecedor.setVerifyInputWhenFocusTarget(false);
        jScrollPane3.setViewportView(tblFornecedor);

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPane2.border.title"))); // NOI18N
        jScrollPane2.setName("jScrollPane2"); // NOI18N

        tblItemPedido.setAutoCreateRowSorter(true);
        tblItemPedido.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "item", "Cod.", "Descrição", "Unid.", "Qtde."
            }
        ));
        tblItemPedido.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tblItemPedido.setEnabled(false);
        tblItemPedido.setName("tblItemPedido"); // NOI18N
        tblItemPedido.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        tblItemPedido.getTableHeader().setResizingAllowed(false);
        tblItemPedido.getTableHeader().setReorderingAllowed(false);
        tblItemPedido.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblItemPedidoMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tblItemPedido);

        btnVoltar.setFont(resourceMap.getFont("btnVoltar.font")); // NOI18N
        btnVoltar.setMnemonic('v');
        btnVoltar.setText(resourceMap.getString("btnVoltar.text")); // NOI18N
        btnVoltar.setName("btnVoltar"); // NOI18N
        btnVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltarActionPerformed(evt);
            }
        });

        pnlBotoes.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pnlBotoes.setName("pnlBotoes"); // NOI18N

        btnConsultar.setFont(resourceMap.getFont("btnConsultar.font")); // NOI18N
        btnConsultar.setMnemonic('n');
        btnConsultar.setText(resourceMap.getString("btnConsultar.text")); // NOI18N
        btnConsultar.setMaximumSize(new java.awt.Dimension(69, 28));
        btnConsultar.setName("btnConsultar"); // NOI18N
        btnConsultar.setPreferredSize(new java.awt.Dimension(69, 28));
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        btnExcluir.setFont(resourceMap.getFont("btnConsultar.font")); // NOI18N
        btnExcluir.setMnemonic('x');
        btnExcluir.setText(resourceMap.getString("btnExcluir.text")); // NOI18N
        btnExcluir.setName("btnExcluir"); // NOI18N
        btnExcluir.setPreferredSize(new java.awt.Dimension(71, 28));
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        jButton1.setFont(resourceMap.getFont("jButton1.font")); // NOI18N
        jButton1.setMnemonic('p');
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setMaximumSize(new java.awt.Dimension(69, 28));
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBotoesLayout = new javax.swing.GroupLayout(pnlBotoes);
        pnlBotoes.setLayout(pnlBotoesLayout);
        pnlBotoesLayout.setHorizontalGroup(
            pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                    .addComponent(btnConsultar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE)
                    .addComponent(btnExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnlBotoesLayout.setVerticalGroup(
            pnlBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addContainerGap(577, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 956, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pnlDadosSolicitante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(pnlBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnVoltar, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(43, 43, 43))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 589, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(410, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(pnlDadosSolicitante, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(pnlBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 304, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnVoltar)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(353, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblItemPedidoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblItemPedidoMouseClicked
        JOptionPane.showMessageDialog(null, "Para alterar os itens da tabela acesse manutenção de Pedidos!");
}//GEN-LAST:event_tblItemPedidoMouseClicked

    private void txtCodigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCodigoFocusLost
        
    }//GEN-LAST:event_txtCodigoFocusLost

    private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
        Object[] options = { "Sim", "Não" };
        int opcao = JOptionPane.showOptionDialog(
                null,
                "Deseja sair da tela de Manutenção de Pedidos?",
                "Saída de Tela",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.WARNING_MESSAGE,
                null,
                options,
                options[0]);

        if (opcao == 0) {
            this.dispose();
        }
}//GEN-LAST:event_btnVoltarActionPerformed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        if (pesquisaManutencaoCotacaoView == null) {
            PesquisaManutencaoCotacaoView frame = new PesquisaManutencaoCotacaoView(this, rootPaneCheckingEnabled);
            frame.setVisible(true);
        }
}//GEN-LAST:event_btnConsultarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        remove_cotacao();
}//GEN-LAST:event_btnExcluirActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        //Caso já tenha sido clicado em consultar, e a cotacao foi selecionada
        if (cot!=null){
            carrega_cotacaoBusca();
            cot = null;
        }
        //Ao iniciar a primeira vez a tela
        else{
            carrega_cotacaoFinal();
        }
    }//GEN-LAST:event_formWindowActivated

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        imprimi_cotacao();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ManutencaoCotacaoView().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnVoltar;
    private javax.swing.JFormattedTextField ftxtEmissao;
    private javax.swing.JFormattedTextField ftxtHoraVencimento;
    private javax.swing.JFormattedTextField ftxtVencimento;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JPanel pnlBotoes;
    private javax.swing.JPanel pnlDadosSolicitante;
    private javax.swing.JTable tblFornecedor;
    private javax.swing.JTable tblItemPedido;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtCondEntrega;
    private javax.swing.JTextField txtCondPgto;
    private javax.swing.JTextField txtDescDepartamento;
    private javax.swing.JTextField txtDescSecao;
    private javax.swing.JTextField txtPedido;
    // End of variables declaration//GEN-END:variables

    private int cotacaoBusca;
    private boolean fornExistente;
    private List<Pessoa> listaPessoas = new ArrayList<Pessoa>();
    private Cotacao cotacao;
    private Pessoa pessoa;
    private ItemPedido itemPedido;
    private DAOManutencaoCotacao daoManutencaoCotacao;
    private int pedidoBusca;
    private List<ItemPedido> listaPedido = new ArrayList();//para receber instancia dos itens do tipo ItemPedido
    private List<ItemPedido> listaItens = new ArrayList<ItemPedido>();//para receber uma listaPed que será utilizada na manipulação da tblItemPedido
    public static String cot =null;
    private PesquisaManutencaoCotacaoView pesquisaManutencaoCotacaoView;

    private void carregar_itens() {
        DefaultTableModel modelo_tbl = (DefaultTableModel) tblItemPedido.getModel();
        modelo_tbl.setNumRows(0);

        itemPedido = new ItemPedido();

        //Preechendo a tabela de itens Pedido
        int tamanho_lista = listaPedido.size();
        for (int i=0; i<tamanho_lista; i++)
        {
            itemPedido = (ItemPedido) listaPedido.get(i);
            modelo_tbl.addRow(new Object[]{itemPedido.getId_itemPedido(),
                                            itemPedido.getProduto().getId_produto(),
                                            itemPedido.getProduto().getNome(),
                                            itemPedido.getUnidade(),
                                            itemPedido.getQuantidade()
                                            });
            listaItens.add(itemPedido);
        }
    }

    private List lista_cotacao() {
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        Criteria c = sessao.createCriteria(Cotacao.class);
        cotacaoBusca = Integer.parseInt(cot);

        c.add(Restrictions.eq("id_cotacao", cotacaoBusca));
        List lista = c.list();

        transacao.commit();
        sessao.close();

        return lista;
    }

    private List<ItemPedido> lista_item() {
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        //Utilizando criteria para instanciar ItemPedido.class
        Criteria crit = sessao.createCriteria(ItemPedido.class).createAlias("pedido", "p");

        //Buscando conforme restrição
        crit.add(Restrictions.eq("p.id_pedido", pedidoBusca));
        List lista = crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();


        transacao.commit();
        sessao.close();

        return lista;
    }

    private void remove_cotacao() {
        Object[] options = { "Sim", "Não" };
        int opcao = JOptionPane.showOptionDialog(
                null,
                "Confirma exclusão da Cotação?",
                "Exclusão de Cotação",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.WARNING_MESSAGE,
                null,
                options,
                options[0]);

        if (opcao == 0) {
            DAOGenerico obj_cotacao = new DAOGenerico(cotacao);

            try{
                if (obj_cotacao.excluir()){
                    carrega_cotacaoFinal();
                }
            }catch(Exception e){
                JOptionPane.showMessageDialog(null, "Não foi possível excluir a Cotação: " +e);
            }
            
        }
    }

    private void carrega_cotacaoFinal() {
        cotacao = new Cotacao();

        //Listando o ultima Cotacao
        List<Cotacao> lista = new ArrayList ();
        lista = lista_ultimaCotacao();
        int tamanho_lista = lista.size();

        //Instanciando Cotacao selecionada
        for (int i=0; i<tamanho_lista; i++)
        {
            cotacao = lista.get(i);
        }

        preenche_objetos();
    }

    private void carrega_cotacaoBusca() {
        cotacao = new Cotacao();

        //Listando Pedido
        List<Cotacao> lista = new ArrayList ();
        lista = lista_cotacao();
        int tamanho_lista = lista.size();

        //Instanciando Pedido selecionado
        for (int i=0; i<tamanho_lista; i++)
        {
            cotacao = lista.get(i);
        }

        preenche_objetos();
    }

    private void preenche_objetos() {
        txtCodigo.setText(String.valueOf(cotacao.getId_cotacao()));
        txtPedido.setText(String.valueOf(cotacao.getPedido().getId_pedido()));
        txtCondEntrega.setText(cotacao.getCondicao_entrega());
        txtCondPgto.setText(cotacao.getCondicao_pagamento());
        txtDescDepartamento.setText(cotacao.getPedido().getSecao().getDepartamento().getDepartamento());
        txtDescSecao.setText(cotacao.getPedido().getSecao().getSecao());
        ftxtHoraVencimento.setText(cotacao.getHora_vencimento());
        

        String formato = "dd/MM/yyyy";
        SimpleDateFormat formatter = new SimpleDateFormat(formato);
        String dataEmissao = formatter.format(cotacao.getData_emissao());
        ftxtEmissao.setText(dataEmissao);

        String dataVencimento = formatter.format(cotacao.getData_vencimento());
        ftxtVencimento.setText(dataVencimento);

        pedidoBusca = Integer.parseInt(txtPedido.getText());

        //Listando os itens do pedido
        listaPedido = lista_item();

        //Preenchendo a tabela com os itens listados
        carregar_itens();

        //Listando os fornecedores
        carregar_fornecedores();

    }

    private List<Cotacao> lista_ultimaCotacao() {
        DAOGenerico obj_dao_generico = new DAOGenerico(cotacao);
        List<Cotacao> lista = new ArrayList();
        lista = obj_dao_generico.executa_query("select_max_id_cotacao");

        return lista;
    }

    private void carregar_fornecedores() {
        pessoa = new Pessoa();

        //Selecionando fornecedores
        List<InclusaoPrecosCotacao> lista = new ArrayList();
        lista = lista_fornecedor();
        int tam_lista = lista.size();

        DefaultTableModel modelo_tbl = (DefaultTableModel) tblFornecedor.getModel();
        modelo_tbl.setNumRows(0);


        //Instanciando fornecedores (Pessoa) e preenchendo-os na tabela
        for (int i=0;i<tam_lista;i++){
            pessoa = lista.get(i).getPessoa();
            //adicionando uma lista de todos as pessoas em "InclusaoPrecosCotacao"
            listaPessoas.add(pessoa);

            //Verificar se já existe o fornecedor a ser acrescentado na tabela
            int idPessoaBuscada = pessoa.getId_pessoa();
            int tamanho_tabela_fornecedor = modelo_tbl.getRowCount();
            for (int j=0; j<tamanho_tabela_fornecedor; j++){
                if (idPessoaBuscada == modelo_tbl.getValueAt(j, 0)){
                    fornExistente = true;
                }
            }
            //Incluir somente os fornecedores que ainda não foram inclusos na tabela
            if (fornExistente == false){
                modelo_tbl.addRow(new Object[]{pessoa.getId_pessoa(),
                                               pessoa.getNome_razao_soc()
                                            });
            }
            fornExistente = false;
        }
    }

    private List<InclusaoPrecosCotacao> lista_fornecedor() {
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        //Utilizando criteria para instanciar Pedido.class
        Criteria crit = sessao.createCriteria(InclusaoPrecosCotacao.class);
        crit.add(Restrictions.eq("cotacao", cotacao));
        List lista = crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

        transacao.commit();
        sessao.close();

        return lista;
    }

    private void imprimi_cotacao() {
        //sequência de métodos para imprimir a cotação
        Connection con = null;
        try {
            //cria a conexao com o banco de dados
            con = ConexaoReport.getConnection();
            //parametro para busca em relatorio Cotacao
            HashMap<String, Integer> parameterMap = new HashMap<String, Integer>();
            //buscando o id_cotacao para passar ao parametro
            Integer cotacaoId = cotacao.getId_cotacao();
            //nome do parametro e o valor é passado ao HashMap
            parameterMap.put("id_cotacao", cotacaoId);
            //parameterMap.put("id_cotacao", 18);

            //PEGA O CAMINHO FISICO DO ARQUIVO .jasper
            String arquivo = "./report/Cotacao.jasper";

            //chama fillReport(caminho fisico, parametros, conexão)
            JasperPrint jp = JasperFillManager.fillReport(arquivo, parameterMap, con);

            //exibe o relatorio com o viewReport
            JasperViewer.viewReport(jp, false);

        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Erro em impressão de Relatorio: " +ex);
        }
        finally {
            try {
                if (!con.isClosed()) {
                    con.close();
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Erro ao fechar conexão: " + e);
            }
        }
    }

}
